package com.aoxun.android.landlord.common;

import com.socks.library.KLog;
import com.aoxun.android.commons.base.BaseActivity;

import java.lang.ref.WeakReference;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * Created by huanglong on 2017/11/21.
 * 基础监听器，主要用于不关注错误处理的情况，如果错误之后还有做特殊处理，请自行实现
 */

public abstract class BaseObserver<T> implements Observer<T> {
    private WeakReference<BaseActivity> baseActivity;
    private boolean isShowLoading;

    public BaseObserver(BaseActivity baseActivity){
        this.baseActivity = new WeakReference<BaseActivity>(baseActivity);
    }

    public BaseObserver(BaseActivity baseActivity,boolean isShowLoading){
        this.baseActivity = new WeakReference<BaseActivity>(baseActivity);
        this.isShowLoading = isShowLoading;
    }


    @Override
    public void onSubscribe(@NonNull Disposable d) {
        KLog.d("start event---->");
        if(isShowLoading && baseActivity!=null && baseActivity.get()!=null) {
            baseActivity.get().getUiDelegate().showLoadingDlg();
        }
    }

    @Override
    public final void onNext(@NonNull T t){
       // KLog.d("onNext:"+Thread.currentThread().getName());
        onSuccess(t);

    }



    @Override
    public void onError(@NonNull Throwable e) {
        KLog.e("onError:"+e.getMessage());
        if(baseActivity!=null && baseActivity.get()!=null) {
            if(isShowLoading)
                baseActivity.get().getUiDelegate().dismissLoadingDlg();

            baseActivity.get().getUiDelegate().toastShort(e != null ? e.getMessage() : "未知异常");
        }
    }

    @Override
    public void onComplete() {
        KLog.d("end event<----");
        if(isShowLoading && baseActivity!=null && baseActivity.get()!=null) {
            baseActivity.get().getUiDelegate().dismissLoadingDlg();
        }
    }


    public abstract void onSuccess(T t);

}
